package com.xinke.juc.sguigu.case02;

import com.xinke.juc.sguigu.util.Sleep;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author：xinke
 * @Date：2025/10/9
 * @Desc: CompletableFuture使用演示
 * CompletableFuture减少阻塞和轮询，可以传入回调对象，当异步任务完成或者发生异常时，自动调用回调对象的回调方法。
 */
@Slf4j
public class C04_CompletableFuture {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            log.info("come in");
            int r = ThreadLocalRandom.current().nextInt(10);
            Sleep.seconds(1);
            if (r > 5) {
                r = 10 / 0;
            }
            log.info("---- 1秒后出结果：【{}】", r);
            return r;
        }, executorService).whenComplete((v, e) -> {
            if (e == null) {
                log.info("计算完成，更新系统【{}】", v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            log.info("异常情况：{}，异常原因：{}", e.getCause(), e.getMessage());
            return null;
        });

        log.info("去完成其他任务");

        executorService.shutdown();
    }
}
